<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
* Crontab
*/
class Crontab extends MY_Controller
{
	
	function __construct()
	{
		parent::__construct();

		// 只允许本地访问
		if (ENVIRONMENT == 'production' && $_SERVER['SERVER_NAME'] != '127.0.0.1') {
			
			exit('error');
		}
	}

	function index() {

		// 启用定时任务
	}

	// 检查产品投资付息
	public function setInterest() {

		// 获取已放款的项目 项目状态[1:未满在投;2:企业还款中;3:企业已还款;4:停止投资;5:等待放款]
		$this->load->model('project_model', 'mpro', 'default');
		$this->load->model('investment_model', 'mint');
		$this->load->model('interest_model', 'minter');
		$list = $this->mpro->get_all(array('audit'              => 1
			                             , 'projectstatus'      => 1
			                             , 'have_money = money' => NULL)
									, 'id,days,title,carrytime,method,rate');

		// 获取放款手机号
		$this->load->model('configs_model', 'mconfig');
		$mobile = $this->mconfig->get('site', 'mobile');

		// 获取项目投资记录
		$pid_arr = array();
		foreach ($list as $p) {
			
			$invs = $this->mint->get_all(array('status' => 0, 'pid' => $p['id']), 'id,aid,money,red_package');

			$c_data  = array();
			$iid_arr = array();
			foreach ($invs as $inv) {
				
				// 获取还款计划
				$c_data = array_merge($c_data, $this->_getInvest($p, $inv));
				array_push($iid_arr, $inv['id']);
			}

			// 插库完成
			if ($c_data) {

				$this->minter->create($c_data, 1);
			}

			if ($iid_arr) {
				
				$this->mint->update(array('status' => 2), array('in' => array('id', $iid_arr)));
			}

			$repaymenttime = date('Y-m-d', strtotime(date('Y-m-d +').$p['days']." days"));
			$this->mpro->update(array('projectstatus' => 5
				                    , 'repaymenttime' => $repaymenttime
				                    , 'interest_at'   => date('Y-m-d H:i:s', strtotime(date('Y-m-d').' +0 days')))
			                  , array('id' => $p['id']));

			// send msg
			if ($mobile) {

				$this->load->library('juhe');
				$this->juhe->sendMsm($mobile,$p['title'],false,43045,'name');
			}
		}

		echo "SUCCESS";
	}

	// 获取还款计划
	private function _getInvest($project, $investment) {

		$invest_list = array();

		// 总周期
		$repaymenttime = date('Y-m-d', strtotime('+ '.$project['days'].' days'));
		
		// 计算总利息
		$invest = round(($project['rate'] * $project['days'] * $investment['money'])/ (year_havedays()*100), 2);
		
		// 红包处理
		$red_package = floatval($investment['red_package']);

		$cycle     = 1;
		$all_cycle = 1;

		// 还款方式 0:按日计息，到期一次性还本付息,1:按日计息，按月付息，到期还款
		if ($project['method']) {
			
			$invest_list_time = array();

			// 付息日未设置为每月1日
			$carrytime = intval($project['carrytime']) ? $project['carrytime'] : 1;
			$s_date = date('Y-m-').$carrytime;

			if (strtotime(date('Y-m-d').' +0 days') < strtotime($s_date)) {
				
				$invest_list_time[] = $s_date;
				$all_cycle++;
			} else if(strtotime(date('Y-m-d').' +0 days') == strtotime($s_date)) {

				$s_date = date('Y-m-d', strtotime($s_date.' +1 months')); 
				$invest_list_time[] = $s_date;
				$all_cycle++;
			}

			while (strtotime($s_date) < strtotime($repaymenttime)) {
				

				$tmp_date = date('Y-m-d', strtotime($s_date." +1 months"));
				$s_date = $tmp_date;

				if (strtotime($repaymenttime) < strtotime($tmp_date)) {
					
					$tmp_date = $repaymenttime;
				}
				$invest_list_time[] = $tmp_date;
				$all_cycle++;
			}

			$invest_c = 0;
			$red_package_c = 0;
			foreach ($invest_list_time as $k => $t) {
				
				if (!$k) {

					$diff = date_diff(date_create(date('Y-m-d').' +0 days'), date_create($t));

				} else {

					$diff = date_diff(date_create($invest_list_time[$k-1]), date_create($t), 1);
				}

				// 计算总利息
				$invest_tmp = round(($project['rate'] * $diff->days * $investment['money'])/ (year_havedays()*100), 2);

				// 最后一期判断
				if (($k+1) == count($invest_list_time)) {
					
					$invest_tmp = $invest - $invest_c;

					// 红包计算
					$invest_tmp   += $red_package;
					$red_package_c = $red_package;

				}
				
				$invest_list[] = array('id'            => null
					                 , 'category'      => 1
					                 , 'pid'           => $project['id']
					                 , 'aid'           => $investment['aid']
					                 , 'iid'           => $investment['id']
					                 , 'cycle'         => $cycle
					                 , 'all_cycle'     => $all_cycle
					                 , 'money'         => $invest_tmp
			                 		 , 'note'          => ''
			                 		 , 'status'        => 0
					                 , 'is_transfer'   => 0
									 , 'repay_at'      => $t
									 , 'repay_real_at' => ''
									 , 'orderid'       => 'FX'.ordernum_time($investment['id']).$k
									 , 'request_no'    => ''
				                 	 , 'create_at'     => date('Y-m-d H:i:s')
					                 , 'red_package'   => $red_package_c);
				$invest_c += $invest_tmp;
				$cycle++;
			}
		} else {

			// 红包计算
			$invest += $red_package;

			$all_cycle++;

			// 付息
			$invest_list[] = array('id'            => null
				                 , 'category'      => 1
				                 , 'pid'           => $project['id']
				                 , 'aid'           => $investment['aid']
				                 , 'iid'           => $investment['id']
				                 , 'cycle'         => $cycle
				                 , 'all_cycle'     => $all_cycle
				                 , 'money'         => $invest
			                 	 , 'note'          => ''
		                 		 , 'status'        => 0
				                 , 'is_transfer'   => 0
				                 , 'repay_at'      => $repaymenttime
								 , 'repay_real_at' => ''
								 , 'orderid'       => 'FX'.ordernum_time($investment['id'])
								 , 'request_no'    => ''
				                 , 'create_at'     => date('Y-m-d H:i:s')
				                 , 'red_package'   => $red_package);
			$cycle++;

		}

		// 还款
		$invest_list[] = array('id'            => null
			                 , 'category'      => 2
			                 , 'pid'           => $project['id']
			                 , 'aid'           => $investment['aid']
			                 , 'iid'           => $investment['id']
			                 , 'cycle'         => $cycle
			                 , 'all_cycle'     => $all_cycle
			                 , 'money'         => $investment['money']
		                 	 , 'note'          => '还款'
	                 		 , 'status'        => 0
			                 , 'is_transfer'   => 0
			                 , 'repay_at'      => $repaymenttime
							 , 'repay_real_at' => ''
							 , 'orderid'       => 'HK'.ordernum_time($investment['id'])
							 , 'request_no'    => ''
			                 , 'create_at'     => date('Y-m-d H:i:s')
			                 , 'red_package'   => 0);
		
		// 返回
		return $invest_list;
	}

	// 提现失效检查
	public function withdrawCheck(){

		$this->load->model("withdraw_model",'mwith','default');
		$limit_time = date("Y-m-d,H:i:s",time()-1000);
		$where  = array("status"=>0,"create_at <="=>$limit_time);
		$u_data = array("status"=>-1);
		$this->mwith->update($u_data,$where);
		echo "SUCCESS";
	}

	// 充值失效检查
	public function rechargeCheck(){
		
		$this->load->model("pay_model",'mpay','default');
		$limit_time = date("Y-m-d,H:i:s",time()-1000);
		$where  = array("status"=>0,"create_at <="=>$limit_time);
		$u_data = array("status"=>-1);
		$this->mpay->update($u_data,$where);
		echo "SUCCESS";
	}

	// 检查余额
	public function checkUserAssets ($id=false) {

		$where['chinaid_check'] = 1;
		if ($id) {
			
			$where['id'] = intval($id);
		}

		$this->load->model('account_model', 'macc', 'default');
		$this->load->model('investment_model', 'minv');
		$this->load->model('withdraw_model', 'mw');
		$this->load->model('pay_model', 'mp');
		$users = $this->macc->get_all($where);

		// 校验account money
		$investmentc = 0;
		$payc        = 0;
		$withdrawc   = 0;
		$interestc   = 0;

		if ($users) {
			
			foreach ($users as $user) {
				
				$inv = $this->minv->get_one(array('aid' => $user['id']), 'sum(money) as money,sum(interest_yet) as interest');
				$wd  = $this->mw->get_one(array('aid' => $user['id'], 'status' => 1), 'sum(money) as money');
				$pay = $this->mp->get_one(array('aid' => $user['id'], 'status' => 1), 'sum(money) as money');
				
				$u_data = array();

				if ($inv['money'] != $user['investmentc']) {
					
					$u_data['investmentc'] = $inv['money'];
				}
				
				if ($pay['money'] != $user['payc']) {
					
					$u_data['payc'] = $pay['money'];
				}

				if ($wd['money'] != $user['withdrawc']) {
					
					$u_data['withdrawc'] = $wd['money'];
				}

				if ($inv['interest'] != $user['interestc']) {
					
					$u_data['interestc'] = $inv['interest'];
				}

				if ($u_data) {
					
					$this->macc->update($u_data, array('id' => $user['id']));

					// 更新数据
					$this->cache->delete('Cache:info:user:'.$user['id']);
                    $this->cache->delete('Cache:info:funds:assets:'.$user['id']);
				}
			}
		}

		// 校验红包

		// return success
		echo 'SUCCESS';
	}

	// 发送短信
	public function sendNotice () {

		$key = 'Cache:crontab:sendNotice';
		if ($this->cache->get($key)) {
			
			echo "ERROR, SENDING MSM";
			return FALSE;
		}
		$this->cache->save($key, 1, 300);
		$this->load->model('msm_log_model', 'mmmsm', 'default');
		$list = $this->mmmsm->get_all(array('create_at >' => date('-1 hours'), 'status' => 0));

		if ($list) {
			
			$this->load->library('juhe');
			$ids = array();

			// 类型[0:注册等验证码类短信;1:满标通知后台放款2:投资成功;3:放款;4:付息/还款]
			$tpl = array('', '43045', '43296', '43295', '43297');
			foreach ($list as $k => $v) {
				
				if(! isset($tpl[$v['type']])) continue;
				$msg_c = explode(',', $v['sendMsg']);
				$content['user'] = $msg_c[0];
				$content['name'] = $msg_c[1];
				$result = $this->juhe->sendMsmTask($v['mobile'], $tpl[$v['type']], $content);

				if ($result) {
					
					$ids[] = $v['id'];
				}
			}

			if ($ids) {
				
				$this->mmmsm->update(array('status' => 1, 'send_at' => date('Y-m-d H:i:s')), array('in' => array('id', $ids)));
			}
			$this->cache->delete($key);

			echo "SUCCESS";
		} else {

			echo "NO TASK DOING";
		}
	}
}